<template>
  <el-dialog
    :title="deptUserManageDialogTitle"
    :visible.sync="dialogVisible"
    width="59%"
    top="10vh"
    append-to-body
    :before-close="closeDeptUserDialogHandle"
    :close-on-click-modal="false"
  >

    <el-table
      highlight-current-row
      max-height="450"
      v-loading="dataLoad"
      element-loading-text="部门关联用户数据加载中"
      element-loading-spinner="el-icon-loading"
      :data="deptUserTableData"
      @selection-change="(val) => this.deptUserSelection = val"
      ref="deptUserTable"
    >
      <el-table-column type="selection" header-align="center" align="center" width="50"></el-table-column>
      <el-table-column prop="deptName" header-align="center" align="center" label="所属部门" ></el-table-column>
      <el-table-column prop="username" header-align="center" align="center" label="用户名称" ></el-table-column>
      <el-table-column prop="status" header-align="center" align="center" label="状态" >
        <template v-slot="scope">
          <el-tag :type="scope.row.status === 0 ? 'success' : 'danger'">
            {{ scope.row.status === 0 ? '可用' : '不可用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" header-align="center" align="center" label="关联时间" width="140"></el-table-column>
      <el-table-column prop="createUser" header-align="center" align="center" label="操作用户" ></el-table-column>
      <el-table-column
        fixed="right"
        header-align="center"
        align="center"
        label="操作"
        >
        <template v-slot="scope">
          <el-button :disabled="loading" type="text" icon="el-icon-delete" size="small" @click="deleteDeptUserRelationHandle(scope.row.userId)" class="danger-color">解除关联</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @current-change="currentChangeHandle"
      :current-page="pageIndex"
      :page-size="pageSize"
      :total="totalNum"
      layout="total, prev, pager, next, jumper"
      class="paging">
    </el-pagination>

    <span slot="footer" class="dialog-footer">
      <el-button @click="closeDeptUserDialogHandle">关 闭</el-button>
      <el-button :disabled="loading || deptUserSelection.length === 0" type="danger" @click="deleteDeptUserRelationHandle(undefined)">批量解除</el-button>
    </span>
  </el-dialog>
</template>

<script>
  export default {
    name: "dept-user-manage",
    props: {
      // 弹出框是否显示
      dialogVisible: {
        type: Boolean,
        default: false
      },
    },
    data() {
      return {
        // 部门数据对象
        dept: {
          // 部门主键
          deptId: undefined,
          // 部门名称
          deptName: undefined,
        },
        // 部门关联用户列表
        deptUserList: [],
        // 表格显示的数据列表
        deptUserTableData: [],
        // 部门关联用户表格被选中的数据
        deptUserSelection: [],
        // 当前展示页码
        pageIndex: 1,
        // 当前页显示个数
        pageSize: 8,
        // 当前一级部门数量
        totalNum: 0,
        // 弹出框标题
        deptUserManageDialogTitle: undefined,
        // 数据是否加载[false-不加载 true-加载]
        dataLoad: false,
        // 按钮是否可被点击[false-可以被点击 true-不可被点击]
        buttonLoad: false,
      }
    },
    computed: {
      // 数据加载中
      loading() {
        return this.dataLoad || this.buttonLoad
      }
    },
    methods: {
      /**
       * 初始化部门关联用户管理弹出框方法
       * @param {Object} dept 部门数据对象
       */
      initDeptUserManageDialog(dept) {
        this.deptUserManageDialogTitle = '部门关联用户管理（' + dept.deptName + "）"

        let deptObj = this.dept
        deptObj.deptId = dept.deptId
        deptObj.deptName = dept.deptName

        this.getDeptUserList()
      },
      /**
       * 获取部门关联的用户列表方法
       */
      getDeptUserList() {
        // 开始表格数据加载
        this.dataLoad = true
        this.$axios.$get('/sys/dept-user/list', { params: { deptId: this.dept.deptId }})
          .then(({ data}) => {
            this.deptUserList = data
            this.totalNum = data.length

            // 分页显示部门关联用户列表
            this.pageDeptUserList()
          })
          .catch(() => {})
          .finally(() => {
            // 表格数据加载结束
            this.dataLoad = false
          })

      },
      /**
       * 对部门关联的用户列表进行分页操作
       */
      pageDeptUserList() {
        let deptUserList = this.deptUserList
        // 构造分页参数
        let start = (this.pageIndex - 1) * this.pageSize,
            end = Math.min(start + this.pageSize, this.totalNum);
        // 分页截取
        this.deptUserTableData = deptUserList.slice(start, end);
      },
      // 当前页
      currentChangeHandle (val) {
        if (this.pageIndex === val) {
          return
        }
        this.pageIndex = val
        this.pageDeptUserList()
      },
      /**
       * 删除部门与用户关联关系事件
       * @param {string} userId 用户主键
       */
      deleteDeptUserRelationHandle(userId) {
        let userIds = new Set();
        if (!!userId) {
          userIds.add(userId)
        } else {
          for (let deptUser of this.deptUserSelection) {
            userIds.add(deptUser.userId);
          }
        }
        // 按钮不可被点击
        this.buttonLoad = true
        this.$axios.$delete('/sys/dept-user/delete', { data: [...userIds] })
          .then(() => {
            // 清除本地缓存中的数据
            this.deleteDeptUserData(userIds)

            this.notify('success', '操作成功', "成功删除部门与用户关联关系")
          })
          .catch(() => {})
          .finally(() => {
            // 按钮恢复可点击
            this.buttonLoad = false
          })
      },
      /**
       * 删除部门与用户本地缓存数据列表中的数据
       * @param {Set} userIds 用户主键集合
       */
      deleteDeptUserData(userIds) {
        let deptUserList = this.deptUserList, index = 0;

        for (let deptUser of deptUserList) {
          if (!userIds.has(deptUser.userId)) {
            // 移位未被删除的数据
            deptUserList[index++] = deptUser;
          }
        }
        // 删除本地数据
        deptUserList.splice(index, deptUserList.length - index);

        this.totalNum = deptUserList.length
        let pageIndex = Math.ceil(deptUserList.length / this.pageSize)
        this.pageIndex = Math.min(this.pageIndex, pageIndex === 0 ? 1 : pageIndex);
        // 重新加载表格数据
        this.pageDeptUserList()
      },
      /**
       * 关闭部门与用户管理弹出框事件
       */
      closeDeptUserDialogHandle() {
        this.$emit('close-dept-user-dialog', this.deptUserList.length)
      }
    }
  }
</script>

<style scoped>
  .paging {
    text-align: right;
    margin: 7px;
  }
</style>
